package com.wwf;

import com.wwf.util.*;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.I0Itec.zkclient.ZkClient;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author wwf
 * @date 2021年01月07日 13:57:08
 */
public class RPCConumer {
    /**
     * 创建当前cpu可用核数的线程池
     */
    private  ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    private  UserClientHandler  userClientHandler;
    private  String ip;
    private  int port;
    private  String hostnode;
    public ExecutorService getService() {
        return service;
    }
    public RPCConumer(String ip,int port) {
        this.ip = ip;
        this.port = port;
    }
    public String getHostnode() {
        return hostnode;
    }

    public void setHostnode(String hostnode) {
        this.hostnode = hostnode;
    }
    public String getIp() {
        return ip;
    }

    public int getPort() {
        return port;
    }

    public Object creatProxy(final Class<?> serviceClass, final RpcRequest rpcRequest){
        Object o = Proxy.newProxyInstance(RPCConumer.class.getClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if(userClientHandler == null) initClient();
                rpcRequest.setClassName(serviceClass.getName());
                rpcRequest.setMethodName(method.getName());
                rpcRequest.setParameterTypes(method.getParameterTypes());
                rpcRequest.setParameters(args);
                rpcRequest.setRequestid("userServiceImpl");
                userClientHandler.setPara(rpcRequest);
                Object obj =   service.submit(userClientHandler).get();
                userClientHandler.setResult("");
                return obj;
            }
        });
        return  o;
    }

    private  void initClient(){
         userClientHandler = new UserClientHandler();
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap = bootstrap.group(eventExecutors);
        bootstrap.channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new RpcEncode(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(userClientHandler);
                    }
                });
        try {
            bootstrap.connect(ip,port).sync();
            System.out.println("客户端连接到服务端地址为："+ip+":"+port);
        } catch (InterruptedException exception) {
            exception.printStackTrace();
        }
    }
}
